package com.qiange.controller;

import com.qiange.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {

//        System.out.println(file);
        //获取上传文件的文件名
        String originalFilename = file.getOriginalFilename();
        //取到文件的后缀名,originalFilename.lastIndexOf("."),取到最后一个点的开始索引
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileName = UUID.randomUUID() + suffix;

//        System.out.println(fileName);
        //判断文件夹是否存在，如果不存在进行创建
        File dirFile = new File(basePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.success(fileName);
    }

    /**
     * 下载图片
     * @param name
     * @param response
     * 从上传图片的服务器本地文件夹通过IO输入流读取出来然后通过response的输出流将图片信息传输给浏览器
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //读取本地文件夹的图片数据，路径+名字
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(basePath + name));

            ServletOutputStream os = response.getOutputStream();

            int len;
            while ((len = bis.read()) != -1) {
                os.write(len);
            }

            os.close();
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
